package se.perp.c4.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import se.perp.c4.control.Main;
import se.perp.c4.model.Game;

public class StartServerDialog extends javax.swing.JDialog implements CaretListener {

    private final MainMenu mainMenu;

    public StartServerDialog(java.awt.Frame parent, MainMenu mainMenu, String defaultName, String defaultPort, Game.ShelobRule defaultShelobRule) {
        super(parent);

        this.mainMenu = mainMenu;

        setModalityType(DEFAULT_MODALITY_TYPE);
        setDefaultCloseOperation(HIDE_ON_CLOSE);
        setTitle("Start server");

        defaultBg = new JTextField().getBackground();
        initComponents();

        portTextField.setText(defaultPort);
        nameTextField.setText(defaultName);

        portTextField.addCaretListener(this);
        nameTextField.addCaretListener(this);

        if (!isValidPort(portTextField.getText())) {
            portTextField.setBackground(Color.PINK);
            okButton.setEnabled(false);
        }
        switch (defaultShelobRule) {
            case SHELOB_DIES:
                shelobRuleComboBox.setSelectedIndex(0);
                break;
            case SHELOB_FIGHTS_OR_DIES:
                shelobRuleComboBox.setSelectedIndex(1);
                break;
            case SHELOB_STAYS:
                shelobRuleComboBox.setSelectedIndex(2);
                break;
            default:
                break;
        }
        if (parent != null) {
            Dimension osz = parent.getSize();

            setLocation(parent.getX() + (osz.width - getWidth()) / 2,
                    parent.getY() + (osz.height - getHeight()) / 2);
        }

        getRootPane().setDefaultButton(okButton);
        setVisible(true);
    }

    public String getPlayerName() {
        return nameTextField.getText();
    }

    public Choice getChoice() {
        return choice;
    }

    public Game.ShelobRule getShelobRule() {
        int i = shelobRuleComboBox.getSelectedIndex();
        Game.ShelobRule[] rules = {Game.ShelobRule.SHELOB_DIES, Game.ShelobRule.SHELOB_FIGHTS_OR_DIES, Game.ShelobRule.SHELOB_STAYS};
        return rules[i];
    }

    public int getPortNumber() {
        try {
            return Integer.parseInt(portTextField.getText());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    private boolean isValidPort(String text) {
        try {
            int i = Integer.parseInt(text);
            return 1023 < i && i < 65536;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        nameTextField = new javax.swing.JTextField();
        portTextField = new javax.swing.JTextField();
        nameLabel = new javax.swing.JLabel();
        portLabel = new javax.swing.JLabel();
        shelobRulePanel = new javax.swing.JPanel();
        shelobRuleComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        shelobDescr = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        okButton.setMnemonic('O');
        okButton.setText("OK");
        okButton.setActionCommand("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setMnemonic('C');
        cancelButton.setLabel("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        nameTextField.setToolTipText("");

        nameLabel.setText("Your name:");

        portLabel.setText("Port number:");

        shelobRulePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Shelob rule"));

        shelobRuleComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shelob dies if can't return", "Shelob fights light upon return", "Shelob stays if can't return" }));
        shelobRuleComboBox.setToolTipText("Selects the rule interpretation for the Shelob character.");
        shelobRuleComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                shelobRuleComboBoxActionPerformed(evt);
            }
        });

        shelobDescr.setColumns(20);
        shelobDescr.setEditable(false);
        shelobDescr.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
        shelobDescr.setLineWrap(true);
        shelobDescr.setRows(3);
        shelobDescr.setWrapStyleWord(true);
        shelobDescr.setBorder(null);
        jScrollPane1.setViewportView(shelobDescr);

        javax.swing.GroupLayout shelobRulePanelLayout = new javax.swing.GroupLayout(shelobRulePanel);
        shelobRulePanel.setLayout(shelobRulePanelLayout);
        shelobRulePanelLayout.setHorizontalGroup(
            shelobRulePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(shelobRulePanelLayout.createSequentialGroup()
                .addComponent(shelobRuleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(153, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
        );
        shelobRulePanelLayout.setVerticalGroup(
            shelobRulePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(shelobRulePanelLayout.createSequentialGroup()
                .addComponent(shelobRuleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(shelobRulePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameLabel)
                            .addComponent(portLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(cancelButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(portTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                            .addComponent(nameTextField, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(nameLabel)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(shelobRulePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        okButton.getAccessibleContext().setAccessibleName("okButton");
        cancelButton.getAccessibleContext().setAccessibleName("cancelButton");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        choice = Choice.CANCEL;
        mainMenu.setGameAsClientEnabled(true);
        mainMenu.setGameAsServerEnabled(true);
        setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed

    private void shelobRuleComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_shelobRuleComboBoxActionPerformed
        shelobDescr.setText(Game.shelobRuleDescription(getShelobRule()));
    }//GEN-LAST:event_shelobRuleComboBoxActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        choice = Choice.CANCEL.OK;
        setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed
  

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton okButton;
    private javax.swing.JLabel portLabel;
    private javax.swing.JTextField portTextField;
    private javax.swing.JTextArea shelobDescr;
    private javax.swing.JComboBox shelobRuleComboBox;
    private javax.swing.JPanel shelobRulePanel;
    // End of variables declaration//GEN-END:variables
    

    public void caretUpdate(CaretEvent e) {
        boolean pfOk = true;
        int nameLen = nameTextField.getText().length();
        boolean nameOk = 0 < nameLen && nameLen <= Main.MAX_NAME_LENGTH;
        nameTextField.setBackground(nameOk ? defaultBg : Color.PINK);

        if (isValidPort(portTextField.getText())) {
            portTextField.setBackground(defaultBg);
        } else {
            portTextField.setBackground(Color.PINK);
            pfOk = false;
        }
        okButton.setEnabled(pfOk && nameOk);
    }

    public enum Choice {

        OK, CANCEL
    };
    private Choice choice = Choice.CANCEL;
    private final Color defaultBg;
}
